<template>
	<view>
		<view class="page__content">

			<uni-nav-bar :height="0" leftWidth="140rpx" rightWidth="60rpx" :title="titleName" :statusBar="true"
				:border="false" :fixed="true" :showMenuButtonWidth="true">
				<template #left>
					<view class="x-f navbar--left">
						<u-icon name="arrow-left" color="#fff" size="20" @click="goBack"></u-icon>

						<u-icon name="close" color="#fff" size="20" @click="goBack('close')"></u-icon>
					</view>
				</template>

				<template #right>
					<m-bubble type="list" :selectData="formMenus" position="right" topOpsotion="right" bgcRgba="#fff"
						color="#333" @selectFun="TapPopup">
						<u-icon name="more-dot-fill" color="#fff" size="20" class="moremenu"></u-icon>
					</m-bubble>
				</template>
			</uni-nav-bar>

			<view class="page__content__main">
				<!-- 主表card区域 -->
				<view class="common__box__form">
					<view class="common__box__form__card">
						<view class="common__box__form__card__title x-f" @click="uni.$utils.TextCopyFun(mainTitle)">
							<text>{{mainTitle}}</text>

							<uni-icons v-if="mainTitle" fontFamily="CustomFontPlatform" color="#f1f1f1"
								style="margin-left: 4rpx;" size="16">{{uni.$utils.toUniCode('&#xe862;')}}</uni-icons>
						</view>

						<view class="common__box__form__card__field" v-for="(item,index) in mainForm" :key="index">
							<text class="common__box__form__card__field__label">{{item.name}}：</text>
							<view class="common__box__form__card__field__value">
								<text>{{item.value}}</text>
							</view>
						</view>

						<view style="position: absolute;top: 10rpx;right: 10rpx;">
							<up-tag :text="tag.text" v-for="tag in tagForm" :key="tag.text" size="medium" plain
								plainFill shape="circle" :type="tag.type"></up-tag>
						</view>


					</view>
				</view>

				<view v-for="(childForm,index) in childFormList" :key="index"
					style="padding: 10rpx 15rpx;background-color: #fff;">

					<view class="common__box__field">
						<view class="common__box__field__label">
							<text>合计：</text>
						</view>

						<view class="common__box__field__value common__box__field__value-right">
							<text>{{showChildFormTableDataLen()}}</text>
						</view>
					</view>

					<view class="common__box__field"
						v-for="totalFunc in getFilterData(childForm.totalFunctions,(item:any)=>!item.isHidden)"
						:key="totalFunc.colName">
						<view class="common__box__field__label">
							<text>{{totalFunc.colDesc}}</text>
						</view>

						<view class="common__box__field__valuecommon__box__fieldl__value-right">
							<text>{{totalFunc.summaryData}}</text>
						</view>
					</view>
				</view>



				<!-- 吸顶Tab栏 -->
				<up-sticky style="top: 0 !important;box-shadow: 0 8px 11px -19px;">
					<view style="background-color: #fff;margin-top: 20rpx;border-bottom: 1px solid #e5e5e5;">
						<up-tabs keyName="title" :list="TabList" :is-scroll="false" :current="tabCurrent"
							:inactiveStyle="{ fontSize: '28rpx' }" :itemStyle="{height:'88rpx'}" @change="clickTabItem"
							:activeStyle="{ fontSize: '28rpx',color: '#51d0d0', fontWeight: '600', transform: 'scale(1.05)' }"
							lineWidth="60" lineColor="#51d0d0" :scrollable="false">
							<template #TabText="{element,index}">
								<view style="font-size: 28rpx;">{{element.title}}</view>
							</template>
						</up-tabs>
					</view>
				</up-sticky>

				<!-- 商品信息 -->
				<template v-if="tabCurrent == 0">
					<view class="common__box__child">
						<template v-for="(childForm,index) in childFormList" :key="index">

							<view class="common__box__child__card" v-for="(item,idx) in childForm.tableData" :key="idx">
								<view class="common__box__child__card__top">
									<view class="common__box__child__card__top__left__title">
										<template v-if="childForm.hasOwnProperty('titleCol')">
											<template v-if="childForm.titleCol.colType!=2">
												<text class="van-badge">{{ idx+1 }}</text>
												<text>{{ item[childForm.titleCol.colName]}}</text>
											</template>

											<template v-else-if="childForm.titleCol.colType==2">
												<text class="van-badge">{{ idx+1 }}</text>
												<text>{{ showActualValue(item[childForm.titleCol.colName],childForm.titleCol,'') }}</text>
											</template>
										</template>


										<template v-else>
											<text class="van-badge">{{ idx+1 }}</text>
										</template>
									</view>
								</view>

								<view class="common__box__child__card__content">
									<view class="common__box__child__card__content__field"
										v-for="col in childApproveShowFun(childForm.columns)" :key="col.colName">
										<view class="common__box__child__card__content__field__label">
											<text>{{ col.colDesc }}:</text>
										</view>

										<view class="common__box__child__card__content__field__value">
											<template v-if="col.colType==5">
												<m-upload v-model="item[col.colName + '_show']"
													:uploadKey="col.colName" :add="false" :remove="false"
													:imageFormData="{compress:false}"
													:listStyle="{columns: BoxInfoCallBack.num,height:BoxInfoCallBack.height+'rpx',padding:'6px',columnGap:'10px',rowGap:'10px'}"
													cloudType="other"></m-upload>
											</template>

											<!-- 下拉框 -->
											<template v-else-if="col.colType==2">
												<text>{{showActualValue(item[col.colName],col,'') }}</text>
											</template>

											<!-- 文本框 -->
											<template v-else>
												<text>{{item[col.colName]}}</text>
											</template>
										</view>
									</view>
								</view>


							</view>


						</template>
					</view>
				</template>

				<!-- 联查信息，关联单据 -->
				<template v-if="tabCurrent == TabList.length-1">
					<template v-for="(item,index) in objDetailModelList" :key="index">
						<view class="common__box__field" @click="openDetailPage(item)">
							<view class="common__box__field__label">
								<text>{{item.Title}}</text>
							</view>

							<view class="common__box__field__value common__box__field__value-right">
								<text :style="{color:item.APPUrl ? '#4499ec' : '#2e2e2e' }">{{item.BillNO}}</text>
							</view>
						</view>
					</template>
				</template>
			</view>



			<view class="content_bottom1 x-ec " :style="uni.$utils.disposeSafeBottomFun()">
				<!-- 审批流 -->
				<button class="CommonBtnSize workBtn" plain style="margin-left: 10px;" :disabled="!enabledSubmitBtn"
					v-if="
					approvalConfig.isEnableApproval && (!formData.Status || formData.Status==3) && !formData.Approve &&
					workList.filter(function(item:any){ return item.name=='发起审批' }).length==0" @click="startApprove">
					<text>发起审批</text>
				</button>

				<button class="CommonBtnSize workBtn" plain style="margin-left: 10px;" :disabled="!enabledSubmitBtn"
					@click="formApprove"
					v-if="approvalConfig.isEnableApproval && formData.Status == 1 && isCurApproval">
					<text>审批单据</text>
				</button>

				<button class="CommonBtnSize workBtn" plain style="margin-left: 10px;" :disabled="!enabledSubmitBtn"
					@click="cancelApprove" v-if="approvalConfig.isEnableApproval && formData.Status == 1">
					<text>撤销审批</text>
				</button>

				<!-- 当业务按钮存在一项时 -->
				<view v-if="MoreSheetList.length == 1 && btnAllowShowFun(MoreSheetList[0]['name'])">
					<button class="CommonBtnSize workBtn x-c" :class="buttonClasses" :style="buttonStyles"
						:disabled="!enabledSubmitBtn" plain v-for="(btn,index) in MoreSheetList" :key="index"
						style="margin-left: 10px;" @click="selfWorkHandler(btn)">
						{{ btn.name }}
					</button>
				</view>
				<!-- 当存在多项业务按钮时 -->
				<view v-else-if="MoreSheetList.length > 1">
					<!-- <u-button :disabled="!enabledSubmitBtn" class="CommonBtnSize content_bottom_primary_plainBtn"
						style="margin-left: 10px;" @click="openMoreSheet" text="更多"></u-button> -->

					<button class="CommonBtnSize content_bottom_primary_plainBtn" style="margin-left: 10px;"
						:disabled="!enabledSubmitBtn" @click="openMoreSheet">更多</button>
				</view>


				<view>
					<button v-if="btnAllowShowFun('编辑')" :disabled="!enabledSubmitBtn"
						class="CommonBtnSize content_bottom_primary_Btn" style="margin-left: 10px;"
						@click="toEdit">编辑</button>
				</view>
			</view>

		</view>

		<m-loading text="正在渲染" :value="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>

	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, computed, reactive, nextTick } from 'vue';
	import { onLoad, onReady } from "@dcloudio/uni-app";
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, PromiseRequestByUrl, onAllComplete, onError } = useRequestQueue();
	import { useMainStore, useInventoryStore, useUserStore, usePermissionStore } from '@/store';
	const inventoryStore = useInventoryStore();
	const mainStore = useMainStore();
	const userStore = useUserStore();
	const permissionStore = usePermissionStore();
	// import mClUpload from '@/commonPage/components/cl-upload/cl-upload';
	import { run } from '@/commonPage/common/interpreter'
	let layer = uni.$utils.layer;
	import { Task, TimeUnits, TaskOptions, TaskType, TaskTriggerMode, Context } from '@/commonPage/common/task-queue/TaskQueue.ts';


	let titleName = ref("");
	let columns = ref<any>([]);
	let mainTitle = ref("");
	let mainForm = ref<any>([]);
	let tagForm = ref<any>([]);
	let MenuDetail = reactive<any>({});

	let detailName = ref("");
	let keyName = ref("");
	let keyValue = ref("");
	let enabledSubmitBtn = ref(false);
	let showMLoading = ref(true);

	Object.assign(MenuDetail, uni.$utils.deepClone(inventoryStore.MenuDetail));
	detailName.value = MenuDetail.detailName;
	keyName.value = MenuDetail.keyName;
	keyValue.value = MenuDetail.keyValue;
	titleName.value = MenuDetail.detailTitle.replace('列表', '') + '详情';
	mainTitle.value = MenuDetail.dataInfo.titleColName;
	mainForm.value = MenuDetail.dataInfo.showColumnsInfo;
	tagForm.value = MenuDetail.dataInfo.tagColumnsInfo;

	let globalData = reactive<any>({});
	let physicalTableName = ref("");
	let isShowComApproval = ref(false);
	let ApprovalID = ref<number | null>(null);
	let isCurApproval = ref(false);
	let ApprovalSort = ref<number | null>(null);
	let formData = reactive<any>({});




	async function initConfig(objName : string) {
		enabledSubmitBtn.value = false;
		showMLoading.value = true;

		try {
			const ret = await requestByUrl({
				config: {
					baseURL: "/AppFormDetail/GetDataByName"
				},
				url: '',
				method: 'POST',
				data: { objName },
			});

			if (ret.status == 200 && ret.data.ds.length) {
				Object.assign(globalData, uni.$utils.deepClone(ret.data));
				physicalTableName.value = ret.data.ds[0].physicalTableName;

				if (keyName.value && keyValue.value) {
					//显示通用审批流
					let comApprovalConfig =
						"select * from Ba_Audit where isnull(History,0)=0 and SourceTable='" +
						physicalTableName.value + "' and SourceID=" + keyValue.value + ' order by APFlowID desc';

					let row = await requestByUrl({
						config: { baseURL: "/SQLData/QuerySql" },
						url: '',
						method: 'POST',
						data: { sql: comApprovalConfig },
					});
					if (row.status == 200 && row.data.ds.length > 0) {
						isShowComApproval.value = true;
						ApprovalID.value = row.data.ds[0].APFlowID;

						await request({
							url: 'WhetherItCanBeApproved',
							method: 'POST',
							data: {
								P_TableName: physicalTableName.value,
								P_PKValue: keyValue.value
							},
							success(item : any) {
								if (item.data.ds[0].ISSP == 1) {
									isCurApproval.value = true;
									ApprovalSort.value = item.data.ds[0].ApprovalSort;
								}
							}
						});
					}

					await requestByUrl({
						config: { baseURL: "/SQLData/GetTableByKeyId" },
						url: '',
						method: 'POST',
						data: {
							physicalTableName: physicalTableName.value,
							keyName: keyName.value,
							keyValue: keyValue.value
						},
						success(row : any) {
							if (row.status == 200 && row.data.ds.length) {
								let result = row.data.ds[0];
								Object.assign(formData, result);

								let approvalConfig = { isEnableApproval: false };
								if (ret.data.ds[0].hasOwnProperty('approvalConfig')) {
									Object.assign(approvalConfig, JSON.parse(ret.data.ds[0].approvalConfig));
								}

								tableConfig({
									childFormList: JSON.parse(ret.data.ds[0].childFormsConfig),
									formDesign: JSON.parse(ret.data.ds[0].formDesignConfig),
									physicalTableName: ret.data.ds[0].physicalTableName,
									workList: JSON.parse(ret.data.ds[0].worksConfig),
									crudList: JSON.parse(ret.data.ds[0].crudConfig),
									approvalConfig: approvalConfig
								});
							}
						}
					});
				}
			}
		} catch (error) {
			//TODO handle the exception
		}

	}

	let MoreSheetList = ref<any>([]);
	// 点击底栏自定义按钮
	function selfWorkHandler(work : any) {
		if (!enabledSubmitBtn.value) {
			return;
		}
		enabledSubmitBtn.value = false;
		if (work.script.includes('buttonCoreTask(')) {
			selfWorkTaskHandler(
				work.script,
				'formData',
				{
					uni,
					formData,
					work,
				}
			);
			return;
		}

		function task1() {
			return new Promise((resolve : any, reject : any) => {
				try {

					let script = work.script.replace(/vm\./g, '');
					script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'formData$1');
					script = script.replace(/enabledSubmitBtn/g, 'enabledSubmitBtn.value');




					// eval(script);

					run(`${script}`, {
						// 注入UniApp环境的API（如uni对象）
						uni: uni,
						formData: formData,
						post,
						layer: uni.$utils.layer,
						work,
						refreshPage,
						enabledSubmitBtn
					})

					resolve();

				} catch (error) {
					reject(error);
				}
			});
		};


		task1().then(() => {
			enabledSubmitBtn.value = true;
			uni.$utils.hideLoading();
		}).catch((error : any) => {
			enabledSubmitBtn.value = true;
			// uni.$utils.hideLoading();
			// uni.showToast({
			// 	title: JSON.stringify(error),
			// 	icon: 'error'
			// })
			// console.error('An error occurred:', error);
		})
	};

	// 点击更多按钮 --- 业务按钮
	function openMoreSheet() {
		if (!enabledSubmitBtn.value) {
			return;
		}

		let benArr = MoreSheetList.value.map((item : any) => {
			return item.name
		})

		uni.showActionSheet({
			itemList: benArr,
			success: function (res) {

				selfWorkHandler(MoreSheetList.value[res.tapIndex]);
			},
			fail: function (res) {

				enabledSubmitBtn.value = true;
			}
		});


		// #ifdef APP-HARMONY

		// #endif

		// #ifdef APP-PLUS
		// plus.nativeUI.actionSheet({
		// 	cancel: "取消",
		// 	buttons: MoreSheetList.value
		// }, function (event) {
		// 	let {
		// 		index
		// 	} = event;


		// 	if (index > 0) {

		// 		selfWorkHandler(MoreSheetList.value[index - 1]);
		// 	} else {
		// 		enabledSubmitBtn.value = true;
		// 	}
		// });
		// #endif

	}

	let TabList = ref<any>([]);
	let childFormList = ref<any>([]);
	let workList = ref<any>([]);
	let approvalConfig = reactive<any>({});
	let tabCurrent = ref<any>(null);



	async function tableConfig(options : any) {
		if (options.childFormList == null) {
			options.childFormList = [];
		}
		workList.value = options.workList;
		childFormList.value = options.childFormList;
		Object.assign(approvalConfig, options.approvalConfig);
		if (workList.value.length) {
			const permissionDeniedFunctions = permissionStore.filterUnPermissionConfig;
			const buttonConditions = await btn_showCondition1(workList.value);
			const funNamesSet = new Set(permissionDeniedFunctions.map((item : any) => item.FunName));
			const filteredButtons = buttonConditions.filter((item : any) => !funNamesSet.has(item.name));

			MoreSheetList.value = filteredButtons.map((item : any) => ({
				...item,
				title: item.name
			}));
		}

		TabList.value = [];
		for (let i = 0; i < childFormList.value.length; i++) {
			TabList.value.push(childFormList.value[i]);
			childPageInit(childFormList.value[i]);
		}

		if (TabList.value.length) {
			clickTabItem({ index: 0 });
		};

		TabList.value.push({
			title: '关联单据'
		});
		link();
	}

	let APPRoleColChildList = ref<any>(null);

	async function clickTabItem(data : any) {
		tabCurrent.value = data.index;

		if (data.title != '关联单据') {
			const ret = await permissionStore.getAPPRoleColFunByRoleID({
				request: request,
				moduleName: TabList.value[data.index]['name'],
				moduleType: 'formlist',
			});
			if (ret.status === 200) {
				APPRoleColChildList.value = new Map();
				if (Array.isArray(ret?.data?.ds)) {
					for (const row of ret.data.ds) {
						if (row?.ColName !== undefined) {
							APPRoleColChildList.value.set(row.ColName, row);
						}
					}
				}
			};
		}
	};

	function childPageInit(childObj : any) {
		requestByUrl({
			config: { baseURL: "/AppFormList/GetDataByName" },
			url: '',
			method: 'POST',
			data: { objName: childObj.name },
			success(ret : any) {
				if (ret.status == 200) {
					let filterCondition = uni.$utils.isEmpty(ret.data.ds[0]["filterCondition"])
						? ""
						: ret.data.ds[0]["filterCondition"];
					childTableConfig({
						childObj: childObj,
						columns: JSON.parse(ret.data.ds[0]["columnsConfig"]),
						params: {
							isFormList: ret.data.ds[0]["isFormList"],
							physicalTableName: ret.data.ds[0]["physicalTableName"],
							isPaging: ret.data.ds[0]["isPaging"],
							filterCondition,
							defaultOrder: ret.data.ds[0]["defaultOrder"],
							detailName: ret.data.ds[0]["detailName"],
							isFormEdit: false,
							rowClassCol: ret.data.ds[0]["rowClassCol"],
							onReadyCallBack: ret.data.ds[0]["onReadyCallBack"],
							colClassCol: ret.data.ds[0]["colClassCol"]
						}
					});
				}
			}
		});
	}

	function childTableConfig(option : {
		childObj : any;
		columns : any[];
		params : any;
	}) {
		let options = reactive<any>({});
		Object.assign(options, option)

		options.childObj.tableData = [];
		options.childObj.columns = options.columns;

		let filterCondition = '1=1';
		if (options.params.filterCondition) {
			filterCondition += ` and ${options.params.filterCondition}`;
		}

		const connectParamsKey = options.childObj.connectParams;
		const connectParamsValue = formData[connectParamsKey];

		if (!connectParamsValue) {
			filterCondition += " and 1=0 ";
		} else {
			filterCondition += ` and ${connectParamsKey}='${connectParamsValue}'`;
		}

		const titleCols = options.childObj.columns.filter((item : any) => item.isTitle === true);
		if (titleCols.length > 0) {
			options.childObj.titleCol = titleCols[0];
		}

		const isForm = (options.params.isFormList !== undefined
			? options.params.isFormList
			: true).toString();

		requestByUrl({
			config: { baseURL: "/SQLData/GetDataByPhysicalTableNameByQueryPaging_Uniapp" },
			url: '',
			method: 'POST',
			data: {
				tableName: options.params.physicalTableName,
				columnsStr: JSON.stringify([]),
				currentCol: '',
				pageIndex: 1,
				pageSize: 9999,
				isForm,
				filterCondition,
				defaultOrder: options.params.defaultOrder || ''
			},
			success(ret : any) {
				if (ret.status == 200) {
					const tableData = ret.data.ds;

					const filePathColumns = options.childObj.columns.filter(
						(item : any) => item.colName.includes("FilePath")
					);

					if (filePathColumns.length) {

						filePathColumns.forEach((column : any) => {
							tableData.forEach((row : any) => {
								const originalValue = row[column.colName];
								const showField = column.colName + '_show';

								if (!uni.$utils.isEmpty(originalValue)) {
									row[showField] = originalValue.split(',')
										.map((path : string) => {
											path = path.trim();
											path = mainStore.getReadyStaticUrl(path);
											return { path };
										});
								} else {
									row[showField] = [];
								}
							});
						});
					}

					options.childObj.tableData = tableData;
					refreshChildCol(options.childObj);
				}
			}
		});
	}

	function refreshChildCol(childObj : any) {
		childObj.columns.forEach((item : any) => {
			if (item.colType == 2 && item.selDetail.type < 3) {
				let sql = item.selDetail.dataSource;
				let selDetailObj = item.selDetail;
				changeDataAjax(sql, "1=1", function (data : any, requestObj : any) {
					requestObj['sqlDataSource'] = data;
				}, selDetailObj);
			} else if (item.colType == 2 && item.selDetail.type == 3) {
				let valueList : string[] = [];

				childObj.tableData.forEach((row : any) => {
					if (!uni.$utils.isEmpty(row[item.colName])) {
						let kData = row[item.colName].toString().split(',');
						kData.forEach((kItem : any, kIndex : any) => {
							valueList.push("'" + kData[kIndex] + "'");
						});
					}
				});

				if (valueList.length > 0) {
					let selDetailObj = item.selDetail;
					changeDataAjax(item.selDetail.dataSource,
						`${item.selDetail.hiddenValue} in (${valueList.join(',')})`,
						function (data : any, requestObj : any) {
							requestObj['sqlDataSource'] = data;
						}, selDetailObj);
				} else {
					item.selDetail.sqlDataSource = [];
				}
			}
		});
		calSummary(childObj);
	}

	function calSummary(childObj : any) {
		let totalFunctions = childObj.columns.filter((item : any) => item.colTotalFunction);
		childObj["totalFunctions"] = totalFunctions;
		totalFunctions.forEach((item : any) => {
			if (item.colTotalFunction == "sum") {
				let fixNum = 2;
				let totalNum = 0;
				for (let j = 0; j < childObj.tableData.length; j++) {
					const num = parseFloat(childObj.tableData[j][item.colName]);
					totalNum += isNaN(num) ? 0 : num;
				}
				item["summaryData"] = totalNum.toFixed(fixNum);
			}
		});
	}

	let changeDataSource = ref<any>([]);
	function changeDataAjax(datasource : any, query : any, callBack : any, requestObj : any) {
		let dsResult = changeDataSource.value.filter((item : any) =>
			item.datasource == datasource && item.query == query
		);
		if (dsResult.length == 0) {
			let returnData : any[] = [];
			let sql = "select * from (" + datasource + ")t where " + query;

			if (sql.indexOf('@') >= 0) {
				for (const name in formData) {
					const repalceValue = "'" + formData[name] + "'";
					sql = sql.replace(new RegExp("@" + name, "g"), repalceValue);
				}
			}

			requestByUrl({
				config: { baseURL: "/SQLData/GetDataBySql" },
				url: '',
				method: 'POST',
				data: { sql },
				success(ret : any) {
					returnData = ret.data.ds;
					changeDataSource.value.push({
						datasource,
						query,
						data: returnData
					});

					callBack && callBack(returnData, requestObj);
				},
				fail(err : any) {

				}
			});
		}
	}


	//显示下拉数据源中的真实数据
	function showActualValue(value : any, colObject : any, originValue : any) {


		if (colObject.selDetail.sqlDataSource) {
			let curObject = ref<any>([]);
			curObject.value = colObject.selDetail.sqlDataSource.filter(function (item : any) {
				return item[colObject.selDetail.hiddenValue] == value
			});
			if (curObject.value.length > 0) {
				return curObject.value[0][colObject.selDetail.displayValue];
			} else if (originValue) {
				return originValue;
			} else {
				return '';
			}
		} else {
			return '';
		}
		//return '';
	}

	let objDetailModelList = ref<any>([]);

	function link() {
		request({
			url: 'getAppRelatedDocuments',
			method: 'POST',
			data: {
				objName: detailName.value,
				KeyID: formData[keyName.value],
			},
			success(ret : any) {
				if (ret.status == 200) {
					objDetailModelList.value = ret.data.ds;
				}
			}
		});
	};
	// 点击前往关联单据
	function openDetailPage(data : any) {
		if (uni.$utils.isEmpty(data.APPUrl)) {
			return
		}
		let menu = uni.$utils.deepClone(data);
		let menuData = parseQueryString(menu.APPUrl);
		let returnData = {
			detailTitle: menuData['objName'],
			detailName: menuData['objName'],
			keyName: menuData['keyName'],
			keyValue: menuData['keyValue'],
			dataInfo: {}
		};
		inventoryStore.MenuDetail = returnData;
		uni.navigateTo({
			url: menuData['Url']
		})

	};
	function parseQueryString(queryString : string) {
		// 如果queryString不包含"?"，则默认整个字符串为URL部分  
		const [url, queryStringPart] = queryString.split('?');

		// 如果没有查询字符串部分，直接返回包含URL的结果  
		if (!queryStringPart) {
			return {
				Url: url.replace(/\.vue$/, '')
			};
		}
		let params = queryStringPart.split('&').reduce((acc : any, current : any) => {
			let [key, value] = current.split('=');
			acc[key] = value;
			return acc;
		}, {});

		params['Url'] = url.replace(/\.vue$/, '');;
		return params;
	};


	let BoxInfoCallBack = reactive({
		num: 3,
		height: 100
	});


	// 子表数据映射
	function childApproveShowFun(data : any) {

		try {
			if (!uni.$utils.isEmpty(data)) {

				let filterData = data.filter((col : any) => !col.isHidden && !col.isTitle);

				const appRoleColChildMap = APPRoleColChildList.value;
				filterData.forEach((item : any) => {
					const colName = item.colName; // 缓存colName，减少访问次数
					const typeInfo = appRoleColChildMap.get(colName);
					if (typeInfo) {
						const isViewRole = typeInfo.IsViewRole;
						const isEditRole = typeInfo.IsEditRole;
						item.isHidden = !isViewRole;
						item.isReadOnly = !isViewRole && !isEditRole;
					}
				});
				return filterData || [];
			} else {
				return data || [];
			}

		} catch (error) {
			return data || [];
			//TODO handle the exception
		}

	}

	async function btn_showCondition1(data : any) {
		try {
			if (data.length) {
				let filterData = await data.filter((btn : any) => {
					let script = btn.show.replace(/vm\./g, '');
					script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'formData$1');
					if (uni.$utils.isEmpty(script)) {
						return true;
					} else {
						let flash = ref(false);
						const runInfo = `flash.value=${script}`;
						run(runInfo, {
							uni: uni,
							formData: formData,
							approvalConfig: approvalConfig,
							flash: flash,
							layer: uni.$utils.layer,
						});
						return flash.value
					}
				});
				return filterData;
			}
			return [];
		} catch (error) {
			return [];
		}
	}

	let formMenus = [
		{ name: '单据设置', value: '', icon: 'order' },
		{ name: '刷新', value: '', icon: 'reload' }
	];

	function TapPopup(data : any) {
		switch (data.name) {
			case '单据设置':
				inventoryStore.FormColumnSetting = columns.value;
				uni.navigateTo({
					url: '/commonPage/Form/FieldSetting',
					events: { reloadPage: function (data : any) { } }
				});
				break;
			case '刷新':
				// 刷新页面逻辑
				initConfig(detailName.value);
				break;
			default:
				break;
		}
	}

	function showChildFormTableDataLen() {
		if (childFormList.value.length > 0 && childFormList.value[0].tableData) {
			return childFormList.value[0].tableData.length;
		} else {
			return '';
		}
	}
	/**
		 * 过滤数组数据
		 * @param {Array} 过滤数组
		 * @param {Function} 过滤条件
		 * @return {Array} 返回过滤后的数据
		 */
	const getFilterData = (data : any[], filter : (ret : any) => boolean) : any[] => {
		if (uni.$utils.isEmpty(data)) {
			return [];
		} else {
			return data.filter(filter)
		}
	}
	function getNewQueryColumnsByType<T>(array : T[], condition : (item : T) => boolean) : T[] {
		const result = [];
		if (uni.$utils.isEmpty(array)) [];
		for (const item of array) {
			if (condition(item)) {
				result.push(item);
			}
		}
		return result;
	}

	function goBack(str : any = 'back') {
		if (str == 'close') {
			let routes = getCurrentPages();
			let routePageCurrent = mainStore.appConfigInfo.routePageCurrent;
			let backNum = routes.length - routePageCurrent;
			uni.navigateBack({ delta: backNum });
		} else {
			uni.navigateBack();
		}
	}


	// 判断当前按钮是否允许显示
	function btnAllowShowFun(str : string) {
		const filterUnPermissionConfig = permissionStore.filterUnPermissionConfig;
		// 检查是否存在任何项的 FunName 与传入的字符串相匹配
		const isFunctionDenied = filterUnPermissionConfig.some((item : any) => item.FunName === str);
		return !isFunctionDenied;
	};
	//进入编辑区域
	function toEdit() {
		if (!enabledSubmitBtn.value) {
			return;
		}
		inventoryStore.MenuDetail = uni.$utils.deepClone(MenuDetail)


		uni.navigateTo({
			url: '/commonPage/Form/Edit'
		})
	}

	/**
	 * 发起审批
	 */
	function startApprove() {
		uni.$utils.layer.alert("暂未开放此功能！")

	};
	function formApprove() {
		uni.$utils.layer.alert("暂未开放此功能！")
	};
	function cancelApprove() {
		uni.$utils.layer.alert("暂未开放此功能！")
	};

	let UserInfo = userStore.UserInfo;
	function post(sql : string, param ?: any, callBack ?: any, errorCallBack ?: any) {
		param["sql"] = sql;


		if (!uni.$utils.isEmpty(UserInfo)) {

			if (!param.hasOwnProperty("P_UserID")) {
				param.P_UserID = UserInfo.UserID;
			}
			if (!param.hasOwnProperty("P_UserName")) {
				param.P_UserName = UserInfo.UserName;
			}
			if (!param.hasOwnProperty("P_UserCode")) {
				param.P_UserCode = UserInfo.UserCode;
			}
		};
		requestByUrl({
			config: { baseURL: "/SQLData/QuerySql" },
			url: '',
			method: 'POST',
			data: param,
			success(ret : any) {
				callBack && callBack(ret);
			},
			fail(err : any) {

				errorCallBack && errorCallBack(err)
				// layer.alert(JSON.stringify(err))
			}
		});
	};


	// 通用刷新
	async function refreshPage() {
		await initConfig(detailName.value);
		uni.$emit('refreshToApprove'); // 刷新审批待办

		uni.$emit('FormInitToRefresh', { // 触发列表、详情
			keyID: formData[keyName.value]
		});
	}

	onAllComplete(() => {

		showMLoading.value = false;
		enabledSubmitBtn.value = true;
	});

	onReady(() => {

		// 监听刷新
		uni.$on('refreshToIndex', () => {
			refreshPage();
		});

		// 监听list回写的数据
		uni.$on('newListData', (ret) => {
			if (!uni.$utils.isEmpty(ret)) {
				tagForm.value = ret.data;
			}
		});
	})

	onLoad(() => {
		initConfig(detailName.value);
	});

	onMounted(() => {
		setTimeout(() => {
			tabCurrent.value = 0;
			let getSystemInfoSync = uni.getSystemInfoSync();
			let backData = uni.$utils.calculateAdaptiveLayout(getSystemInfoSync.screenWidth, 20)
			Object.assign(BoxInfoCallBack, backData);

		}, 300);

		nextTick(() => {
			uni.createSelectorQuery().select('.CommonBtnSize').boundingClientRect(rect => {
				// that.btnStyle = rect

				Object.assign(btnStyle, rect);

			}).exec();
		});

	})

	let btnStyle = reactive<any>({})

	const buttonClasses = computed(() => {
		return {
			'small-font': btnStyle.width < 80,
			'disabled': !enabledSubmitBtn.value
		}
	});
	const buttonStyles = computed(() => {
		return {
			height: btnStyle.height ? `${btnStyle.height}px` : 'auto',
			'line-height': '20px'
		}
	});


	const scriptUsedAPI = {
		Task,
		enabledSubmitBtn,
		TimeUnits,
		TaskType,
		TaskTriggerMode,
		saveRowByTask,
		buttonCoreTask,
		pageRefreshTask,
		pageRedirect,
		postSqlByTask,
		post,
		inventoryStore,
		mainStore,
		userStore,
		permissionStore,
		layer: uni.$utils.layer,
	};
	async function selfWorkTaskHandler(
		script : string,
		dataName : string,
		injectedAPI : { [key : string] : any }
	) : Promise<string> {
		try {


			script = script.replace(/vm\./g, '');
			script = script.replace(/(?<![A-Za-z'"])(\[\s*['"])/g, `${dataName}$1`);
			Object.assign(injectedAPI, scriptUsedAPI);
			injectedAPI.injectedAPI = injectedAPI;





			return await run(script, injectedAPI) ?? ""; // 注入UniApp环境的API（如uni对象）
		} catch (error : unknown) {
			enabledSubmitBtn.value = true;
			uni.$utils.hideLoading();
			if (error.message) {
				let message = error.message;
				if (
					message.startsWith("the id of task:") &&
					message.endsWith(" is already exist!")
				) {
					message = '重复操作';
				}
				layer.alert(message, {
					icon: 2,
					title: '错误信息',
					btn: ['确定']
				});
			}
			console.error('An error occurred:', error);
			return "";
		}
	}

	async function saveRowByTask(
		chainName : string,
		beforeTask : string[],
		timeSuffix : string,
	) : Promise<string> {
		const action = async (context : Context, data ?: unknown) => {
			return true;
		}
		const opt = {
			action,
			addNow: true,
			id: 'saveRowByTask' + timeSuffix,
			chainName,
			beforeTask,
			triggerMode: TaskTriggerMode.Or,
		} as TaskOptions;
		const task = new Task(opt);
		return task.id;
	}

	function buttonCoreTask(
		buttonType : string,
		sql : string,
		params : { [key : string] : any },
		beforeTask : string[],
		timeSuffix : string,
	) : string {
		return postSqlByTask(sql, params, beforeTask, timeSuffix);
	}

	function postSqlByTask(
		sql : string,
		params : { [key : string] : any },
		beforeTask : string[],
		timeSuffix : string,
	) : string {
		const chainName = Task.getTask(beforeTask[0])?.chainName;
		if (!chainName) {
			throw new Error("[postSqlByTask]: can't get chainName By beforeTask")
		}
		const action = async (context : Context, data ?: unknown) => {


			params = await
				getCurrentParams(params, context.data?.injectedAPI);
			params["sql"] = sql;
			if (!uni.$utils.isEmpty(UserInfo)) {

				if (!params.hasOwnProperty("P_UserID")) {
					params.P_UserID = UserInfo.UserID;
				}
				if (!params.hasOwnProperty("P_UserName")) {
					params.P_UserName = UserInfo.UserName;
				}
				if (!params.hasOwnProperty("P_UserCode")) {
					params.P_UserCode = UserInfo.UserCode;
				}
			};


			return requestByUrl({
				config: { baseURL: "/SQLData/QuerySql" },
				url: '',
				method: 'POST',
				data: params,
			}).then((data) => {
				if (data?.status === 200) {
					return data.data;
				} else if (data?.status === 500) {

					layer.alert(data.msg, {
						icon: 2,
						title: '错误信息',
						btn: ['确定']
					});
					throw new Error(data.msg);
				} else {
					throw new Error(String(data));
				}
			});
		}
		const opt = {
			action,
			addNow: true,
			id: chainName + '-postSqlByTask' + timeSuffix,
			type: TaskType.REQUEST,
			chainName,
			beforeTask,
			triggerMode: TaskTriggerMode.Or,
		} as TaskOptions;
		const task = new Task(opt);
		return task.id;
	}

	async function getCurrentParams(
		params : { [key : string] : any },
		injectedAPI : { [key : string] : any } = {},
	) : Promise<{ [key : string] : any; }> {
		const currentParams : { [key : string] : any } = {};
		for (const key in params) {
			if (params.hasOwnProperty(key)) {
				currentParams[key] = await run(params[key], injectedAPI);
			}
		}
		return currentParams;
	}


	function pageRefreshTask(
		id : string,
		chainName : string,
		beforeTask : string[],
		triggerMode : TaskTriggerMode = TaskTriggerMode.And,
	) : Task {
		const action = async (context : Context, data ?: unknown) => {
			await refreshPage();
			return true;
		}
		const opt = {
			action: action,
			addNow: true,
			id,
			chainName,
			beforeTask,
			triggerMode,
		} as TaskOptions;
		return new Task(opt);
	}

	function pageRedirect(
		menuOpt : { [key : string] : any },
		url : string
	) {
		inventoryStore.MenuDetail = menuOpt;
		uni.navigateTo({ url });
	}
</script>


<style lang="scss">
	/* #ifdef MP-WEIXIN */
	view {
		box-sizing: border-box;
		margin: 0;
		padding: 0;
	}

	/* #endif */

	/* #ifndef MP-WEIXIN */
	* {
		box-sizing: border-box;
		margin: 0;
		padding: 0;
	}

	/* #endif */

	.van-badge {
		margin: 0px 5px;
		background-color: #51d0d0;
		color: #fff;
		display: block;
		min-width: 25px;
		height: 25px;
		line-height: 25px;
		// padding: 3px;
		float: left;
		vertical-align: middle;
		border-radius: 8px;
		text-align: center;
	}

	.page__content {
		height: 100vh;
		background-color: #f9f9f9;

		// .navbar--left {
		// 	:deep(.u-icon) {
		// 		margin-right: 20rpx !important;
		// 	}
		// }

		.content_main {
			flex: 1;
			overflow: auto;
			position: relative;


			.TopCard {
				background-color: #4499ec;

				.CardInfo {
					flex: 3;
				}

				.CardTag {
					position: absolute;
					right: 20px;
					top: 25rpx;

				}
			}
		}
	}

	.common__box {

		&__child {
			&__card__content {
				&__field {
					&__label {
						color: #999;
					}

					&__value {
						margin-left: 10rpx;
						color: #999;
					}
				}
			}

		}


		&__field {
			background-color: #fff;
			padding: 8rpx 15rpx;

			&__label {
				color: #999;
			}

			&__value {
				margin-left: 10rpx;
				color: #999;
			}
		}

	}


	.content_bottom1 {
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		height: 70px;
		line-height: 70px;
		padding: 6px 15px;
		// border-top: 1px solid #efefef;
		box-shadow: 1px 0 12px -9px #333;
		z-index: 99;

		// uni-button {
		// 	margin-left: initial !important;
		// 	margin-right: initial !important;
		// }

		.workBtn {
			border-color: #ddd !important;
			margin-left: 10px !important;

			&.small-font {
				font-size: 12px !important;
			}

			&:not(.small-font) {
				font-size: 14px;
			}
		}
	}
</style>